package fr.univ.surveyonline.datastore;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

import com.google.appengine.api.datastore.Key;


public final class PMF {
	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional"); 
	
	private PMF(){}


	private static PersistenceManager getPersistenceManager() {
		return pmfInstance.getPersistenceManager();
	}
	
	public static List<?> getAllFromClass(Class<?> classe) {
		return executeQuery("select from " + classe.getName());		
	}
	
	@SuppressWarnings("unchecked")
	public static List<?> executeQuery(String query) {
		PersistenceManager pm = getPersistenceManager();
		List<Object> list = (List<Object>) pm.newQuery(query).execute();
		List<Object> res = new ArrayList<Object>();
		res.addAll(list);
		pm.close();
		return res;
	}
	
	public static void makePersistent(Object o) {
		PersistenceManager pm = getPersistenceManager(); 
		pm.makePersistent(o);
		pm.close();
	}
	
	public static Object getElementByKey(Key key) {
		PersistenceManager pm = getPersistenceManager(); 
		Object o = pm.getObjectById(key);
		pm.close();
		return o;
	}
	
	@SuppressWarnings("unchecked")
	public static Object getElementById(Class<?> classe,long id) {
		PersistenceManager pm = getPersistenceManager(); 
		String query = "select from "
			+ classe.getName() + " where key==" + id;
		List<Object> list = (List<Object>) pm.newQuery(query).execute();
		
		if (list.size() != 1) {
			throw new IllegalStateException("id inexistant");
		}
		Object o = list.get(0);
		pm.close();
		return o;
	}
	
	@SuppressWarnings("unchecked")
	public static Object getElementById(Class<?> classe,String id) {
		PersistenceManager pm = getPersistenceManager(); 
		String query = "select from "
			+ classe.getName() + " where key=='" + id + "'";
		List<Object> list = (List<Object>) pm.newQuery(query).execute();
		
		if (list.size() != 1) {
			throw new IllegalStateException("id inexistant");
		}
		Object o = list.get(0);
		pm.close();
		return o;
	}
	
	public static void delete(Object o) {
		PersistenceManager pm = getPersistenceManager();
		pm.makePersistent(o);
		pm.deletePersistent(o);
		pm.close();
	}
	
	public static void deleteAll(List<?> col) {
		PersistenceManager pm = getPersistenceManager(); 
		pm.makePersistentAll(col);
		pm.deletePersistentAll(col);
		pm.close();
	}
	
	@SuppressWarnings("unchecked")
	public static void deleteClass(Class<?> classe) {
		PersistenceManager pm = getPersistenceManager();
		
		String query = "select from " + classe.getName();
		List<Object> list = (List<Object>) pm.newQuery(query).execute();
		pm.makePersistentAll(list);
		pm.deletePersistentAll(list);
		
		pm.close();
	}
}